import requests
from loguru import logger
from work.get_100_keys import get_100_keys_id
from work.search_site_list import get_site_id
import time
import random

def dele_keys_word(company_info, user):
    cookies = user['cookies']
    matching_project = get_site_id(company_info=company_info, user=user)
    if matching_project == 0:
        return f"账号: {user['account']} -----> 没有 {company_info['company_name']} 该项目"
    keyword_ids = get_100_keys_id(matching_project=matching_project, cookies=cookies)
    if keyword_ids:
        headers = {
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
            "cache-control": "no-cache",
            "origin": "https://online.seranking.com",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "referer": "https://online.seranking.com/admin.site.rankings.site_id-8286431.html?ref=project_select_clicked",
            "sec-ch-ua": "\"Google Chrome\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "x-requested-with": "XMLHttpRequest"
        }
        url = "https://online.seranking.com/api.keywords.html"
        files = {
            'do': (None, 'deleteKeywords'),
            'site_id': (None, str(matching_project['site_id'])),
            'keyword_ids': (None, str(keyword_ids)),
            'group_ids': (None, '')
        }
        retry_count = 0
        while retry_count < 3:
            try:
                res = requests.post(url, headers=headers, cookies=cookies, files=files, timeout=5)
            except Exception as e:
                logger.error(f"{user['account']}: {company_info['company_name']} ----> 请求超时: {e}")
                time.sleep(random.randint(1, 2))
                retry_count += 1
                continue
            data = res.json()
            keys_list = keyword_ids.split(',')
            if res.status_code == 200:
                logger.success(f"账号: {user['account']}: {matching_project['company_name']}: 共有{len(keys_list)}个 -----> 关键词删除成功")
                return 1
            else:
                logger.error(f"账号: {user['account']}: {matching_project['company_name']} -----> 删除失败: {data['error']} 状态码: {res.status_code}")
                return 0
    else:
        logger.info(f"账号: {user['account']}: {matching_project['company_name']} -----> 没有关键词需要删除")
        return 2